import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import store from "@/store";

Vue.use(VueRouter);

const oldPushMethod = VueRouter.prototype.push;
//2. 覆盖原来的push方法 重写push
VueRouter.prototype.push = function (
  location,
  onComplate = () => { },
  onAbort = () => { }
) {
  //内部使用的还是以前的push方法,但是我们给添加了处理异常的回调函数
  return oldPushMethod.call(this, location, onComplate, onAbort);
};

//1. 保存旧的replace方法
const oldReplaceMethod = VueRouter.prototype.replace;
//2. 覆盖原来的push方法 重写push
VueRouter.prototype.replace = function (
  location,
  onComplate = () => { },
  onAbort = () => { }
) {
  //内部使用的还是以前的push方法,但是我们给添加了处理异常的回调函数
  return oldReplaceMethod.call(this, location, onComplate, onAbort);
};

const router = new VueRouter({
  mode: "history",
  routes
});

const whitePath = [
  "login",
  "home",
  "register",
  "search",
  "detail",
  "addCartSuccess",
  "shopCart",
];
router.beforeEach(async (to, from, next) => {
  // token校验
  // console.log("1", 1);
  const token = store.state.user.token
  if (token) {
    // console.log("2", 2);
    // 判断是否为登陆页，是则直接去home页
    if (to.name === "login") {
      // console.log("3", 3);
      next("/home")
    } else {
      // console.log("4", 4);
      // 判断是否有用户信息
      const isUserInfo = !!store.state.user.userInfo.nickName
      // 有的话直接放行
      if (isUserInfo) {
        // console.log("5", 5);
        next()
      } else {
        try {
          // console.log("6", 6);
          // 用户信息不存在，获取用户信息
          await store.dispatch("user/getUserInfo")
          // 存在直接放行
          next()
        } catch (e) {
          // console.log("7", 7);
          // 获取用户信息失败，直接去登录页
          store.dispatch("user/getResetUser");
          next(`/login?redirect=${to.name}`);
        }
      }
    }
    // token不存在
  } else {
    // 判断去的地方是否是白名单，去的地方不需要登陆则直接放行
    if (whitePath.includes(to.name)) {
      // console.log("8", 8);
      next()
    } else {
      // console.log("9", 9);
      // 否则再次登陆
      next("/login?redirect = ${to.name}")
    }
  }
})

export default router;
